//
//  CheatsClassesFlowLayout.m
//  MDC
//
//  Created by Kang on 16/8/12.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "CheatsClassesFlowLayout.h"

@implementation CheatsClassesFlowLayout

- (instancetype)init {
    
    if(self = [super init]) {
        //
        self.itemSize = CGSizeMake(CHEATS_Item_W, CHEATS_Item_H);
        //控制头部到 view 的距离
        self.headerReferenceSize = CGSizeMake(CHEATS_SCREEN_W, CHEATS_Padding_V);
    }
    return self;
}


- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    /**
     *  使布局范围变化
     */
    return YES;
}

- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    
    CGFloat offsetY = self.collectionView.contentOffset.y;
    NSArray * attrArray = [super layoutAttributesForElementsInRect:rect];
    CGFloat collectionViewFrameHeight = self.collectionView.frame.size.height;
    CGFloat collectionViewContentHeight = self.collectionView.contentSize.height;
    CGFloat ScrollViewContentInsetBottom = self.collectionView.contentInset.bottom;
    CGFloat bottomOffset = offsetY + collectionViewFrameHeight - collectionViewContentHeight - ScrollViewContentInsetBottom;
    NSInteger numOfItems = self.collectionView.numberOfSections;
    
    for (UICollectionViewLayoutAttributes * attr in attrArray) {
        if (attr.representedElementCategory == UICollectionElementCategoryCell) {
            CGRect cellRect = attr.frame;
            if (offsetY <= 0) {
                CGFloat distance = fabs(offsetY)/CHEATS_SpringFactor;
                cellRect.origin.y += offsetY + distance * (attr.indexPath.section + 1);
                
            } else if (bottomOffset > 0) {
                CGFloat distance = bottomOffset/CHEATS_SpringFactor;
                cellRect.origin.y += bottomOffset - distance * (numOfItems - attr.indexPath.section);
            }
            attr.frame = cellRect;
        }
    }
    return attrArray;
}


@end
